var common = require('../../../util/common');
var aoi = require('../../../util/aoi');

module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
    this.sceneId = this.app.getCurServer().scene;
    this.channelService = this.app.get('channelService');
    this.backendSessionService = this.app.get("backendSessionService");
    this.channel = this.channelService.getChannel('scene_' + this.sceneId, true);
    this.cachedb = this.app.get('cachedb');
    this.aoi = new aoi(50, 50);
};

// 进入场景
Handler.prototype.join = function(player, cb) {
    var self = this;
    this.backendSessionService.getByUid(player.sid, player.uid, function(err, sessions) {
        if (err || sessions === 'undefined' || sessions.length === 0) {
            common.invokeCallback(cb, new Error('get backend session failed!'));
            return;
        }

        self.aoi.playerEnter(player, function(err, result) {
            if (err) {
                common.invokeCallback(cb, new Error('player enter failed!'));
                return;
            }
            if (result.length > 0) {
                // 广播玩家进入场景的信息
                var param = {
                    route: 'onJoin',
                    uid: player.uid,
                    name: player.name,
                    sid: player.sid
                };
                self.channelService.pushMessageByUids(param, result);
            }

            var memberlist = [];
            for (var index in result) {
                var member = {
                    uid: result[index].uid,
                    sid: result[index].sid,
                    name: result[index].name
                };
                memberlist.push(member);
            }
            // 将场景的信息发送给玩家
            self.channelService.pushMessageByUids('onUserInfo', {members: memberlist}, [{
                uid: player.uid,
                sid: player.sid
            }]);
        });

        // 将场景ID写入session
        sessions[0].set('scene', self.sceneId);
        sessions[0].push('scene', function(err) {
            if (err) {
                console.error('set scene for session service failed! error is : ' + err.stack);
            }
        });

        // 将玩家添加进场景channel
        self.channel.add(player.uid, sessions[0].frontendId);

        self.channelService.pushMessageByUids('onJoinScene', {code: 200, msg: '进入场景' + self.sceneId}, [{
            uid: player.uid,
            sid: sessions[0].frontendId
        }]);
        common.invokeCallback(cb, false);
    });
};

// 离开场景
Handler.prototype.leave = function(uid, sid, cb) {
    var self = this;
    // 离开场景channel
    self.channel.leave(uid, sid);

    self.aoi.playerLeave(uid, function(err, result) {
        if (err) throw new Error('player leave failed!');
        if (result.length > 0) {
            var param = {
                route: 'onLogout',
                uid: uid,
                sid: sid
            };
            self.channelService.pushMessageByUids(param, result);
        }
    });
    common.invokeCallback(cb);
};

Handler.prototype.chat = function(msg, uid, cb) {
    var self = this;
    common.launchFiber(function() {
        var data = self.cachedb.syncGet(uid);
        var player = JSON.parse(data);
        var param = {
            route: 'onChat',
            type: 2,
            msg: player.name + ': ' + msg.msg
        };
        self.channel.pushMessage(param);
    });
    common.invokeCallback(cb);
};